<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Constants\ErrorCode;
use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Constants\QuestionnaireAnswerConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Mapper\QuestionnaireMapper;
use App\CustHub\Model\ChCrowdSendingLoop;
use App\CustHub\Model\ChSmartQuestionnaire;
use App\CustHub\Model\ChSmartQuestionnaireAnswer;
use App\CustHub\Model\ChSmartQuestionnaireStatistic;
use App\Exception\BusinessException;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;

class QuestionnaireService extends AbstractService
{
    public function __construct(QuestionnaireMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function saveQuestionnaire($uid,$mainUid,$corpId,array $data,$id = 0)
    {
        Db::beginTransaction();
        try{
            $res =  ChSmartQuestionnaire::saveQuestionnaire($uid,$mainUid,$corpId,$data,$id);
            Db::commit();
            return $res;
        } catch(\Throwable $ex){
            Db::rollBack();
            throw new BusinessException((int)$ex -> getCode(),$ex -> getMessage());
        }
    }


    public function answer($questionnaire_id,$openId,$nickname,$avatar,$source,array $data)
    {
        Db::beginTransaction();
        try{
            $data = [
                ['id'=>124,'question_type' => 'radio','content'=>132,'option_id'=> 132],
                ['id'=>125,'question_type' => 'checkbox','content'=>136,'option_id'=> 136],
                ['id'=>127,'question_type' => 'company','content'=>'言午网络']
            ];
            $res =  ChSmartQuestionnaireAnswer::branchAnswer(0,$openId,0,0,$questionnaire_id,$nickname,$avatar,$source,$data,0);
            Db::commit();
            return $res;
        } catch(\Throwable $ex){
            Db::rollBack();
            throw new BusinessException((int)$ex -> getCode(),$ex -> getMessage());
        }
    }

    public function getDetailWithAnswer($id,$openId)
    {
        $detail =  ChSmartQuestionnaire::query() -> with(['items' => function($q){
            $q -> with([
                'option' => function($q){
                    $q ->  orderBy('sort') -> select(['item_id','id','name','value','is_other']);
                }
            ]) ->  orderBy('sort') -> select(['questionnaire_id','question_type','id','content']);
        }]) -> where('id',$id) ->  first();
        if(empty($detail)){
            throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        }
        $detail = $this -> formatDetail($detail -> toArray());
        foreach ($detail['content'] as $key => $item){
            $answerContent = ChSmartQuestionnaireAnswer::query() -> where('item_id',$item['id']) -> where('open_id',$openId) -> select(['content','option_id']) -> first();
            $detail['content'][$key]['answer_content'] = $answerContent;
        }
        return $detail;
    }


    public function getDetail($id)
    {
       $detail =  ChSmartQuestionnaire::query() -> with(['items' => function($q){
            $q -> with([
                'option' => function($q){
                      $q ->  orderBy('sort') -> select(['item_id','id','name','value','is_other','select_total']);
                }
            ]) ->  orderBy('sort') -> select(['questionnaire_id','question_type','id','content']);
        }]) -> where('id',$id) ->  first();
       if(empty($detail)){
           throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
       }
       return $this -> formatDetail($detail -> toArray());
    }

    public function userList($questionnaire_id)
    {
        return ChSmartQuestionnaireAnswer::query() -> where('questionnaire_id',$questionnaire_id) -> groupBy('open_id') -> selectRaw("MIN(nickname) as nickname,MIN(avatar) as avatar,MIN(customer) as customer,MIN(corp_id) as corp_id,MIN(source) as source,MIN(created_at) as created_at") -> get();
    }

    public function itemAnalyse($id)
    {
        $detail =  ChSmartQuestionnaire::query() -> with(['items' => function($q){
            $q -> with([
                'option' => function($q){
                    $q ->  orderBy('sort') -> select(['item_id','id','name','value','is_other','select_total']);
                }
            ]) ->  orderBy('sort') -> select(['questionnaire_id','question_type','id','content']);
        }]) -> where('id',$id) ->  first();
        if(empty($detail)){
            throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        }
        return $this -> formatDetail($detail -> toArray(),true);
    }

    public function upStatistic($questionnaire_id,$source,$open_id,$s_type)
    {
        ChSmartQuestionnaireStatistic::upStatistic($questionnaire_id,$source,$open_id,$s_type);
        return true;
    }


    public function statistic($questionnaire_id)
    {
       $staticArray =  ChSmartQuestionnaireStatistic::query() -> where('questionnaire_id',$questionnaire_id) -> groupBy(['source','s_type']) -> selectRaw("count(1) as total,source,s_type") -> get();
       $newStaticArray = [];
       $baseArray = [
           [
               'source' => 1,
               'today' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ],
               'total' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ]
           ],
           [
               'source' => 2,
               'today' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ],
               'total' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ]
           ],
           [
               'source' => 3,
               'today' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ],
               'total' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ]
           ],
           [
               'source' => 4,
               'today' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ],
               'total' => [
                   'click_total'=>0,
                   'write_total'=>0,
                   'submit_total'=>0
               ]
           ]
       ];
       $baseTotalArray = [
           'today' => [
               'click_total'=>0,
               'write_total'=>0,
               'submit_total'=>0
           ],
           'total' => [
               'click_total'=>0,
               'write_total'=>0,
               'submit_total'=>0
           ]
       ];
       foreach ($staticArray as $item){
           if($item['source'] == 1){
               $item['s_type'] == 1 && $baseArray[0]['total']['click_total'] = $baseArray[0]['total']['click_total'] + $item['total'];
               $item['s_type'] == 2 && $baseArray[0]['total']['write_total'] = $baseArray[0]['total']['write_total'] + $item['total'];
               $item['s_type'] == 3 && $baseArray[0]['total']['submit_total'] = $baseArray[0]['total']['submit_total'] + $item['total'];
           }
           if($item['source'] == 2){
               $item['s_type'] == 1 && $baseArray[1]['total']['click_total'] = $baseArray[1]['total']['click_total'] + $item['total'];
               $item['s_type'] == 2 && $baseArray[1]['total']['write_total'] = $baseArray[1]['total']['write_total'] + $item['total'];
               $item['s_type'] == 3 && $baseArray[1]['total']['submit_total'] = $baseArray[1]['total']['submit_total'] + $item['total'];

           }
           if($item['source'] == 3){
               $item['s_type'] == 1 && $baseArray[2]['total']['click_total'] = $baseArray[2]['total']['click_total'] + $item['total'];
               $item['s_type'] == 2 && $baseArray[2]['total']['write_total'] = $baseArray[2]['total']['write_total'] + $item['total'];
               $item['s_type'] == 3 && $baseArray[2]['total']['submit_total'] = $baseArray[2]['total']['submit_total'] + $item['total'];
           }
           if($item['source'] == 4){
               $item['s_type'] == 1 && $baseArray[3]['total']['click_total'] = $baseArray[3]['total']['click_total'] + $item['total'];
               $item['s_type'] == 2 && $baseArray[3]['total']['write_total'] = $baseArray[3]['total']['write_total'] + $item['total'];
               $item['s_type'] == 3 && $baseArray[3]['total']['submit_total'] = $baseArray[3]['total']['submit_total'] + $item['total'];
           }
       }
       $start = date("Y-m-d",time())." 00:00:00";
       $end = date("Y-m-d",time())." 23:59:59";
       $todayArray =  ChSmartQuestionnaireStatistic::query()
           -> where('questionnaire_id',$questionnaire_id)
           -> whereBetween('created_at',[$start,$end])
           ->groupBy(['source','s_type']) -> selectRaw("count(1) as total,source,s_type") -> get();
        foreach ($todayArray as $item){
            if($item['source'] == 1){
                $item['s_type'] == 1 && $baseArray[0]['today']['click_total'] = $baseArray[0]['today']['click_total'] + $item['total'];
                $item['s_type'] == 2 && $baseArray[0]['today']['write_total'] = $baseArray[0]['today']['write_total'] + $item['total'];
                $item['s_type'] == 3 && $baseArray[0]['today']['submit_total'] = $baseArray[0]['today']['submit_total'] + $item['total'];
            }
            if($item['source'] == 2){
                $item['s_type'] == 1 && $baseArray[1]['today']['click_total'] = $baseArray[1]['today']['click_total'] + $item['total'];
                $item['s_type'] == 2 && $baseArray[1]['today']['write_total'] = $baseArray[1]['today']['write_total'] + $item['total'];
                $item['s_type'] == 3 && $baseArray[1]['today']['submit_total'] = $baseArray[1]['today']['submit_total'] + $item['total'];

            }
            if($item['source'] == 3){
                $item['s_type'] == 1 && $baseArray[2]['today']['click_total'] = $baseArray[2]['today']['click_total'] + $item['total'];
                $item['s_type'] == 2 && $baseArray[2]['today']['write_total'] = $baseArray[2]['today']['write_total'] + $item['total'];
                $item['s_type'] == 3 && $baseArray[2]['today']['submit_total'] = $baseArray[2]['today']['submit_total'] + $item['total'];
            }
            if($item['source'] == 4){
                $item['s_type'] == 1 && $baseArray[3]['today']['click_total'] = $baseArray[3]['today']['click_total'] + $item['total'];
                $item['s_type'] == 2 && $baseArray[3]['today']['write_total'] = $baseArray[3]['today']['write_total'] + $item['total'];
                $item['s_type'] == 3 && $baseArray[3]['today']['submit_total'] = $baseArray[3]['today']['submit_total'] + $item['total'];
            }
        }
       foreach ($baseArray as $item){
           $baseTotalArray['total']['click_total'] = $baseTotalArray['total']['click_total'] + $item['total']['click_total'];
           $baseTotalArray['total']['write_total'] = $baseTotalArray['total']['write_total'] + $item['total']['write_total'];
           $baseTotalArray['total']['submit_total'] = $baseTotalArray['total']['submit_total'] + $item['total']['submit_total'];

           $baseTotalArray['today']['click_total'] = $baseTotalArray['today']['click_total'] + $item['today']['click_total'];
           $baseTotalArray['today']['write_total'] = $baseTotalArray['today']['write_total'] + $item['today']['write_total'];
           $baseTotalArray['today']['submit_total'] = $baseTotalArray['today']['submit_total'] + $item['today']['submit_total'];
       }
       return ['total_static'=>$baseTotalArray,'source_static' => $baseArray];
    }



    public function formatDetail($detail,$analyse = false)
    {
        $newDetail = [];
        $newContent = [];
        $content = $detail['items'];
        foreach ($content as $item){
            $total = 0;
            if($analyse && in_array($item['question_type'],[QuestionnaireAnswerConstants::HEADER,QuestionnaireAnswerConstants::FOOTER,QuestionnaireAnswerConstants::TEXT,QuestionnaireAnswerConstants::IMAGE])){
                continue;
            }
            $newItem = [];
            $newItem['question_type'] = $item['question_type'];
            $newItem['id'] = $item['id'];
            $newItem['content'] = $item['content'];
            $newItem['option'] = [];
            if(!empty($item['option'])){
                if($analyse){
                    foreach ($item['option'] as $item2){
                        $total += $item2['select_total'];
                    }
                }
                foreach ($item['option'] as $item2){
                    $newOption = [
                        "name" => $item2['name'],
                        "value" => $item2['id'],
                        "is_other" => $item2['is_other'],
                    ];
                    if($analyse){
                        $newOption["total"] =  $item2['select_total'];
                        $newOption['rate'] = $total == 0?0:bcmul($item2['select_total']/$total,100,2);
                    }
                    $newItem['option'][] = $newOption;
                }
            }
            if($analyse){
                if(empty($item['option'])){
                    $answerList = ChSmartQuestionnaireAnswer::query() -> where('item_id',$item['id']) -> select(['nickname','avatar','content','open_id','questionnaire_id']) -> get();
                    $newItem['answer_list'] = $answerList;
                }
                $newItem["total"] =  $total;
            }

            $newContent[] = $newItem;

        }

        $newDetail['id'] = $detail['id'];
        $newDetail['main_uid'] = $detail['main_uid'];
        $newDetail['uid'] = $detail['uid'];
        $newDetail['corp_id'] = $detail['corp_id'];
        $newDetail['status'] = $detail['status'];
        $newDetail['forever'] = $detail['forever'];
        $newDetail['end_at'] = $detail['end_at'];
        $newDetail['link'] = $detail['link'];
        $newDetail['content'] = $newContent;
        return $newDetail;
    }

}